#!/usr/bin/perl -w
# Improve Audio Bible MP3 files from Faith Comes By Hearing (FCBH)
# Copyright (C) 2009  OpenScriptures.org; GPL 3 License
# $Id$
# $URL$

=description

Faith Comes By Hearing (FCBH) produces excellent audio Bibles. The MP3s that they
distribute, however, leave much to be desired:

1. The MP3 files are organized into directories for each book, like "A01_Genesis" or
   "B27_Revelation". This is not so bad, however...
2. The MP3 files aren't named well for ease of use, like "A01___01_Genesis_______C2CEVXXX.mp3"
   and "B27___22_Revelation____C2CEVXXX.mp3".
3. There is no title provided for each of the MP3's and so the unintuative filenames
   end up getting displayed as the track titles, which make them difficult to navigate.
4. Every single MP3 chapter file is assigned to the same album, such as
   "Bible - CEV - Complete - Audio Drama - Contemporary English Version". This makes
   it very difficult to quickly get to the desired chapter since every single
   preceding chapter in the whole Bible must be scrolled past in order to somewhere
   in the middle.

Therefore, this script makes the following improvements to the MP3 files by:

1. Reorganizing the files into new directories, from "A01_Genesis" into "01 - Genesis"
2. Renaming the filenames from
     "A01___01_Genesis_______C2CEVXXX.mp3" to "Genesis 001.mp3" and
     "A19__150_Psalms________C2CEVXXX.mp3" to "Psalms 150.mp3"
3. Assigning each chapter in a book to an album entitled the book's name, so instead of each chapter
   having the same album "Bible - CEV - Complete - Audio Drama - Contemporary English Version"
   the chapters in Genesis are given the album name of "Genesis"
4. The chapter names are changed from being empty to consisting of the book name followed by the
   chapter number. So when viewing the files, the track titles go from being like:
   "A01___01_Genesis_______C2CEVXXX.mp3" to "Genesis 1".
5. The artist is changed from "Faith Comes By Hearing - FCBH" to (for example)
   "CEV Dramatized by FCBH" (this is because the version is stripped from the album name).
6. The track numbers are set to correspond with chapter numbers, so the file "Genesis 009.mp3"
   has the track number 9 of 50. (This ensures that Genesis 10 doesn't come before Genesis 2 in
   an string sort.)
7. Since each of the MP3 files are placed into albums consisting of the book's name,
   viewing a list of the albums by the artist (the Bible version) results in an alphabetical
   list which is not as helpful as the canonical order, and so a special ID3 tag is set which
   sets the album order to the canonical order.

To summarize, the file "Genesis 009.mp3" is changed as follows:

Directory: A01_Genesis
           ==> "01 - Genesis"
Filename: "A01___09_Genesis_______C2CEVXXX.mp3"
          ==> "Genesis 009.mp3" 
Title: null
       ==> "Genesis 9"
Track: null
       ==> 9 of 50
Album: "Bible - CEV - Complete - Audio Drama - Contemporary English Version"
       ==> "Genesis"
Album Sort: null
            ==> "01 - Genesis"

The genre remains "Bible" and the comments and lyrics (chapter text) and other ID3 tags remain the same.

=cut


use strict;
use warnings;
use utf8;
use File::Find;
use File::Copy;
use MP3::Tag;

## Begin Configuration ################################################################

my $artist = "Turkish Mujde (Good News) by FCBH";
my $lang = 'tur';
my $sourceDir = '/Users/westonruter/Music/iTunes/iTunes Music/Faith Comes By Hearing/Turkish Mujde (Good News) Non-Drama';
my $destDir = '/Users/westonruter/Music/iTunes/iTunes Music/Faith Comes By Hearing/Turkish Improved';

## End Configuration ################################################################

my %bookChapterCount = ();
my %originalFileNames = ();

mkdir $destDir if not -e $destDir;

find({
	no_chdir => 1,
	wanted => sub {
		#return if not /jude/i; #DEBUG
		
		#Parse the MP3 file names
		my $originalFileName = $_;
		$originalFileName =~ s{.+/(?=[^/]+)}{};
		if($originalFileName =~ /(\w)(\d+)_+0*(\d+)_([^_]+).+?\.mp3$/i){ #A19__001_Psalms________C2CEVXXX.mp3
			my($testament, $booknum, $chapter, $bookname) = ($1, $2, $3, $4);
			
			#Format book name
			my $bookname_formatted = $bookname;
			$bookname_formatted =~ s{^(\d+)}{$1 };
			$bookname_formatted =~ s{SongofSongs}{Song of Solomon};
			$bookname_formatted =~ s{Thess}{Thessalonians};
			
			##Format Testament (not currently used)
			#if($testament eq 'B'){
			#	$booknum += 39;
			#	$testament = 'NT';
			#}
			#else {
			#	$testament = 'OT';
			#}
			
			$originalFileNames{"$bookname_formatted $chapter"} = $originalFileName;
			
			#Make directory
			my $dirname = sprintf("%02d - %s", $booknum, $bookname_formatted);
			if(not exists $bookChapterCount{$dirname}){
				print "Copying files: $dirname\n";
				$bookChapterCount{$dirname} = 0;
			}
			$bookChapterCount{$dirname}++;
			mkdir "$destDir/$dirname"  if not -e "$destDir/$dirname";
			
			#Copy file over to new directory
			my $filename = sprintf("$destDir/$dirname/%s %03d.mp3", $bookname_formatted, $chapter);
			copy($File::Find::name, $filename);
		}
	}
}, $sourceDir);


#Modify the ID3 tags
chdir($destDir);
foreach my $bookDir (keys %bookChapterCount){
	chdir $bookDir;
	while(<*.mp3>){
		#next if not /jude/i; #DEBUG
		print "$_\n";
		
		/^(.+) 0*(\d+)/;
		my $book = $1;
		my $chapter = $2;
		
		my $mp3 = MP3::Tag->new($_);
		$mp3->get_tags();
		my $id3v2 = $mp3->{ID3v2};
		my $frameIDs_hash = $id3v2->get_frame_ids('truename');
		
		$id3v2->remove_frame("TIT2"); $id3v2->add_frame("TIT2", "$book $chapter");
		$id3v2->remove_frame("TALB"); $id3v2->add_frame("TALB", $book);
		$id3v2->remove_frame("TPE1"); $id3v2->add_frame("TPE1", $artist);
		$id3v2->remove_frame("TSOA"); $id3v2->add_frame("TSOA", "$bookDir"); #Album sort order
		$id3v2->remove_frame("TRCK"); $id3v2->add_frame("TRCK", $chapter . '/' . $bookChapterCount{$bookDir});
		$id3v2->remove_frame("TLAN"); $id3v2->add_frame("TLAN", $lang);
		$id3v2->remove_frame("TOFN"); $id3v2->add_frame("TOFN", $originalFileNames{"$book $chapter"});
		$id3v2->write_tag();
	}
	chdir '..';
}

1;